<template>
    <div :style="carStyle" class="tableClass">
        <div v-if="!showContent" class="defaultText">请在右侧配置数据</div>
        <template v-else>
            <div style="padding:10px ;">
                <el-form ref="searchform" :inline="true" :model="filterForm" :rules="rules" label-width="0" :size="obj.size"
                    v-if="obj.isSearch" class="filterform">
                    <el-form-item prop="beginTime" v-for="(item, index) in fileData" :key="item.key"
                        :prop="'serachData.' + index + '.value'">
                        <el-input v-model="item.value" :placeholder="'搜索' + obj.tableData.searchText[index]" />
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" icon="el-icon-search" @click="findSearchHandle()">搜索</el-button>
                    </el-form-item>
                </el-form>
                <template v-if="obj.isExport">
                    <el-button style="display:inline-block;" type="primary" icon="el-icon-download" @click="exportTableData"
                        :size="obj.size">导出</el-button>
                </template>
            </div>
            <!-- <p class="tabletitle" :style="titleStyle">{{ obj.title }}</p> -->
            <div class="v-table">
                <table class="etable" :style="tableStyle">
                    <thead>
                        <tr>
                            <th class="tableindex" v-if="obj.tableData.isShowIndex" :style="headStyle">序号</th>
                            <th v-for="item in columns" :key="item.id" :style="headStyle">{{ item.name }}</th>
                        </tr>
                    </thead>
                    <tbody>
                        <tr v-for="(item, index) in dataList" :key="index">
                            <td class="tableindex" v-if="obj.tableData.isShowIndex">{{ index + 1 }}</td>
                            <td v-for="(i, index2) in item" :key="index2" :style="dtStyle(index2)">
                                <template v-if="columns[index2].attribute == 3">
                                    <div class="filetd" @click.stop="showFile(i)">{{ jsonDataReturn(i) }}</div>
                                </template>
                                <template v-else>{{ i }}</template>
                            </td>
                        </tr>
                    </tbody>
                </table>
                <el-pagination v-if="!obj.tableData.isHidePage" :current-page.sync="filterForm.pageInfo.page"
                    :page-size="filterForm.pageInfo.pageSize" layout="total, prev,pager, next"
                    :total="filterForm.pageInfo.totalCount" class="tablepages" @size-change="handleSizeChange"
                    @current-change="handleCurrentChange">
                </el-pagination>
            </div>
        </template>
        <div class="gotoViewBtn" v-if="isGotoView" @click="gotoUrl(obj)"></div>
    </div>
</template>

<script>
// import { cardDataLoad, boardLoad } from '@/api/share'
import axios from "axios"

export default {
    Name: "CardTable",
    props: {
        obj: Object,
        isReload: {
            type: Boolean,
            default: false
        },
        isEdit: {
            type: Boolean,
            default: false,
        },
        showfile: Function,
        gotoUrl: Function,
    },
    data() {
        return {
            showContent: false,
            carStyle: {},
            titleStyle: {},
            currentPage1: 0,
            // 用于比对数据是否修改
            dataStr: "",
            // 获取图标数据
            filterForm: {
                pageInfo: {
                    pageSize: 10,
                    page: 1,
                    totalCount: 0
                },
                tableId: 0,
                structureIds: [],
                keyWord: "",
                serachData: [],
            },
            fileData: [],
            timer: null,
            // 表格数据
            columns: [],
            dataList: [],
            tableStyle: {},
            headStyle: {},
        }
    },
    mounted() {
        this.setStyle();

        // #region 搜索框数组
        this.fileData = [];
        if (this.obj.tableData.searchLineId.length) {
            this.obj.tableData.searchLineId.forEach(e => {
                this.fileData.push({
                    key: e,
                    value: ""
                })
            })
        }
        // #endregion

        this.$nextTick(function () {
            this.reloadInfo();
        })

        this.dataStr = JSON.stringify(this.obj.tableData);
    },
    computed: {
        isGotoView() {
            if (this.isEdit == false && this.obj.contactType > 0) {
                if (this.obj.contactType == 1 && this.obj.boardId) {
                    return true;
                }
                if (this.obj.contactType == 2 && this.obj.url) {
                    return true;
                }
            }
            return false;
        }
    },
    methods: {
        // 动态设置表格列样式
        dtStyle(index) {
            if (this.obj.tableData.yList[index]) {
                var tdInfo = this.obj.tableData.yList[index];
                return {
                    color: tdInfo.color2,
                    fontSize: tdInfo.fontSize + "px",
                    fontWeight: tdInfo.fontWeight,
                    fontStyle: tdInfo.fontStyle,
                }
            }
            return {};
        },
        reloadInfo() {
            clearInterval(this.timer);

            // #region
            var beginTime = "";
            var endTime = "";
            const end = new Date();
            const start = new Date();

            // if (this.obj.tableData.filterTimeType == 99) {
            //     beginTime = undefined;
            //     endTime = undefined;
            // } else if (this.obj.tableData.filterTimeType > 0) {
            //     start.setTime(start.getTime() - 3600 * 1000 * 24 * this.obj.tableData.filterTimeType);
            //     beginTime = this.parseTime(start, "{y}-{m}-{d}");
            //     endTime = this.parseTime(end);
            // } else if (this.obj.tableData.filterTimeType == 0) {
            //     beginTime = undefined;
            //     endTime = undefined;
            // } else {
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 15);
            beginTime = this.parseTime(start, "{y}-{m}-{d}");
            endTime = this.parseTime(end);
            // }
            this.filterForm.beginTime = beginTime;
            this.filterForm.endTime = endTime;
            // #endregion

            this.getLineData((dataResult) => {
                // 循环刷新
                this.timedRefresh();
            });
        },
        // 定时刷新
        timedRefresh() {
            var timeSize = 60;
            if (this.obj.tableData.reloadTime) {
                timeSize = this.obj.tableData.reloadTime;
            }

            if (this.isReload) {
                this.timer = setInterval(() => {
                    const end = new Date();
                    this.filterForm.endTime = this.parseTime(end, "{y}-{m}-{d} {h}:{i}:{s}");;

                    this.getLineData();
                }, timeSize * 1000);
            }
        },
        handleSizeChange(val) {
            this.filterForm.pageInfo.pageSize = val;
            this.getLineData();
        },
        handleCurrentChange(val) {
            this.filterForm.pageInfo.page = val;
            this.getLineData();
        },
        setStyle() {
            var style = this.obj.style;

            var backgroundColor = "";
            var backgroundImage = "";

            var tableLayout = "";
            if (this.obj.tableLayout) {
                tableLayout = this.obj.tableLayout;
            }

            // 背景颜色
            if (style.backgroundImage.length) {
                backgroundImage = `url(${style.backgroundImage}`;
            } else if (style.backgroundColor.length > 0) {
                backgroundColor = style.backgroundColor;
            }

            var boxShadow = "";
            if (style.boxShadow) {
                boxShadow = `${style.boxShadow.h}px ${style.boxShadow.v}px ${style.boxShadow.blur}px ${style.boxShadow.spreed}px ${style.boxShadow.color}`
            }

            this.carStyle = {
                boxShadow,
                width: "100%",
                height: "100%",
                // display: "flex",
                backgroundSize: "100% 100%",
                borderStyle: "solid",
                backgroundImage,
                backgroundColor,
                color: style.color,
                fontSize: style.fontSize + "px",
                justifyContent: style.justifyContent,
                alignItems: style.alignItems,
                borderColor: style.borderColor,
                borderWidth: style.borderWidth + "px",
                borderRadius: style.borderRadius + "px",
                fontWeight: style.fontWeight,
                fontStyle: style.fontStyle,
            }

            // #region 新的背景颜色

            if (this.obj.style.bgcolorType == "image") {
                this.carStyle.backgroundImage = backgroundImage;
            } else if (this.obj.style.bgcolorType == "gradient") {
                if (this.obj.style.gradient.isRadial) {
                    this.carStyle.backgroundImage = `radial-gradient(${this.obj.style.gradient.colorStart}, ${this.obj.style.gradient.colorEnd})`;
                } else {
                    this.carStyle.backgroundImage = `linear-gradient(${this.obj.style.gradient.fontAngle}deg, ${this.obj.style.gradient.colorStart}, ${this.obj.style.gradient.colorEnd})`;
                }
            } else {
                this.carStyle.backgroundColor = backgroundColor;
            }

            // #endregion

            this.tableStyle = {
                tableLayout
            }

            if (this.obj.hFontSize) {
                this.headStyle = {
                    color: this.obj.hFontColor,
                    fontSize: this.obj.hFontSize + "px",
                    fontWeight: this.obj.hFontWeight,
                    fontStyle: this.obj.hFontStyle,
                }
            }
            // this.titleStyle = {
            //     justifyContent: style.justifyContent,
            //     // alignItems: style.alignItems,
            // }
        },
        // 搜索数据
        findSearchHandle() {
            this.filterForm.pageInfo.page = 1;

            this.getLineData();
        },
        getLineData(callback) {
            if (this.obj.tableData.orderAsc == 1) {
                this.filterForm.orderAsc = true;
            } else {
                this.filterForm.orderAsc = false;
            }

            if (this.obj.tableData.pageSize) {
                this.filterForm.pageInfo.pageSize = this.obj.tableData.pageSize;
            }

            // #region 搜索条件去空赋值 
            this.filterForm.serachData = [];
            if (this.fileData.length) {
                this.fileData.forEach(e => {
                    if (e.value) {
                        this.filterForm.serachData.push(e)
                    }
                })
            }
            // #endregion

            if (this.obj.tableData.tableId && this.obj.tableData.yList.length) {
                this.showContent = true;

                this.filterForm.tableId = this.obj.tableData.tableId;

                // 获取设置的列数据id
                var idlist = [];
                this.obj.tableData.yList.forEach(e => {
                    if (e.id) {
                        idlist.push(e.id);
                    }
                });

                // 空的列数据就不请求api
                if (!idlist.length) return false;

                this.filterForm.structureIds = idlist;
                if (this.obj.tableData.type != 1) {
                    cardDataLoad(this.filterForm).then((res) => {
                        if (res.data.code == 0) {
                            this.columns = res.data.data.dataResult.columns;
                            this.dataList = res.data.data.dataResult.dataList;

                            this.filterForm.pageInfo.totalCount = res.data.data.pageInfo.totalCount;

                            if (callback) {
                                callback(res.data.data.dataResult);
                            }
                        } else {
                            console.error(res.data.message)
                        }
                    }).catch(() => {
                        clearInterval(this.timer)
                    });
                } else {
                    boardLoad(this.filterForm).then((res) => {
                        if (res.data.code == 0) {
                            this.columns = res.data.data.dataResult.columns;
                            this.dataList = res.data.data.dataResult.dataList;

                            this.filterForm.pageInfo.totalCount = res.data.data.pageInfo.totalCount;
                            if (callback) {
                                callback(res.data.data.dataResult);
                            }
                        } else {
                            console.error(res.data.message)
                        }
                    }).catch(() => {
                        clearInterval(this.timer)
                    });
                }
            }
        },
        // 资源文件展示
        jsonDataReturn(jsonData) {
            if (jsonData) {
                var data = JSON.parse(jsonData);
                return data.name;
            }
            return "";
        },
        showFile(jsonData) {
            if (jsonData) {
                var data = JSON.parse(jsonData);
                // return data.name;
                this.goDetial(data);
            }
            return false;
        },
        goDetial(item) {
            if (this.isEdit) {
                this.$message.error("预览时查看详情");
                return false;
            }
            if (item.type == 0) {
                this.$emit('showfile', { type: 0, url: item.url })
            } else if (item.type == 1) {
                this.$emit('showfile', { type: 1, url: item.url })
            } else if (item.type == 2) {
                axios({
                    method: "GET",
                    url: process.env.VUE_APP_FILE_GETPATH,
                    params: { fileid: item.url },
                    timeout: 10000,
                }).then((res) => {
                    if (res.data.code == 0) {
                        window.open(res.data.data.path);
                    } else {
                        this.$message.error(res.data.msg);
                    }
                })
            }
        },
        // 日期筛选触发查询函数
        dateSearch(beginTime, endTime) {
            clearInterval(this.timer);
            this.filterForm.beginTime = beginTime;
            this.filterForm.endTime = endTime;
            this.filterForm.isOnlie = false;

            this.getLineData();
        },

        // #region 数据导出
        exportTableData() {
            if (this.obj.tableData.tableId && this.obj.tableData.yList.length) {
                const loading = this.$loading({
                    lock: true,
                    text: '数据正在导出……',
                    spinner: 'el-icon-loading',
                    background: 'rgba(0, 0, 0, 0.7)'
                });

                this.filterForm.tableId = this.obj.tableData.tableId;
                var idlist = [];
                this.obj.tableData.yList.forEach(e => {
                    if (e.id) {
                        idlist.push(e.id);
                    }
                });
                this.filterForm.structureIds = idlist;

                var queryData = Object.assign({}, this.filterForm);
                queryData.pageInfo.pageSize = 9999;
                queryData.pageInfo.page = 1;

                if (this.obj.tableData.type != 1) {
                    cardDataLoad(queryData).then((res) => {
                        if (res.data.code == 0) {
                            var itemdata = res.data.data.dataResult.columns;
                            var listdata = res.data.data.dataResult.dataList;
                            this.exportDowlad(itemdata, listdata);

                        } else {
                            console.error(res.data.message)
                        }
                    }).catch(() => {
                        loading.close();
                    });
                } else {
                    boardLoad(queryData).then((res) => {
                        if (res.data.code == 0) {
                            var itemdata = res.data.data.dataResult.columns;
                            var listdata = res.data.data.dataResult.dataList;
                            this.exportDowlad(itemdata, listdata);

                        } else {
                            console.error(res.data.message)
                        }
                    }).catch(() => {
                        loading.close();
                    });
                }
            }
        },
        exportDowlad(columns, datalist) {
            var self = this;
            import("@/vendor/Export2Excel").then((excel) => {
                const tHeader = columns.map(e => { return e.name; });

                excel.export_json_to_excel({
                    header: tHeader,
                    data: datalist,
                    filename: "表格导出数据",
                    autoWidth: true,
                    bookType: "xlsx",
                });
                this.exportFormVisible = false;
                self.$loading().close();
            });
        },
        // #endregion
    },
    watch: {
        obj: {
            deep: true,  // 深度监听
            handler(newVal, oldVal) {
                this.setStyle();

                // 数据改变了 动态更新echart
                if (JSON.stringify(this.obj.tableData) != this.dataStr) {
                    this.dataStr = JSON.stringify(this.obj.tableData);

                    if (this.obj.tableData.tableId) {

                        // #region 重构搜索框数组
                        this.fileData = [];
                        if (this.obj.tableData.searchLineId.length) {
                            this.obj.tableData.searchLineId.forEach(e => {
                                this.fileData.push({
                                    key: e,
                                    value: ""
                                })
                            })
                        }
                        // #endregion

                        this.reloadInfo();
                    }
                }
            }
        }
    },
    beforeDestroy() {
        clearInterval(this.timer)
    }
}
</script>

<style lang="scss">
.tableindex {
    text-align: center;
}

.tabletitle {
    width: 100%;
    padding: 5px;
    display: flex;
    margin: 0;
    z-index: 1;
}

.tableClass {
    width: 100%;
    height: 100%;
    overflow: hidden;
    position: relative;

    /* padding-top: 30px; */
    .el-form-item {
        margin-bottom: 0;
    }

    .filterform {
        display: inline;
    }

    .el-pager li,
    .el-pagination .btn-next,
    .el-pagination button:disabled {
        background: none !important;
    }
}

.v-table {
    width: 100%;
    height: calc(100% - 30px);
    font-size: 12px;
    overflow-y: auto;
}

.etable {
    width: 100%;
    border-collapse: collapse;
    table-layout: fixed;
}

.etable tr {
    /* border: 1px solid #cccccc; */
}

.etable td,
.etable th {
    /* overflow: hidden; */
    /* white-space: nowrap; */
    /* text-overflow: ellipsis; */
    border: 0;
    /* border-right: 1px solid #cccccc; */
    text-align: center;
    // height: 30px;
    font-size: 14px;
    max-width: 150px;
    font-weight: normal;
    padding: 12px 0;
}

.etable tr:nth-child(even) {
    // background: #f5f5f5;
}

.etable tr:hover {
    // background: #daedfd;
}

.etable thead tr {
    background: none;
    // border-bottom: solid 1px #e8e8e8;
    font-size: 14px;
    color: #777;
}

.etable thead tr:hover {
    background: none;
}

.tableClass .el-pagination button:disabled,
.tableClass .el-pagination .btn-prev,
.tableClass .el-pagination .btn-next {
    background: none;
}

.tablepages {
    width: 100%;
    display: flex;
    margin-top: 5px;
    justify-content: flex-end;
    overflow: auto;
}

.filetd {
    cursor: pointer;
    text-decoration: underline;
}

.filetd {
    max-width: 130px;
    overflow: hidden;
    white-space: break-spaces;
    word-break: break-all;
    font-size: 12px;
    padding: 5px 0;
    margin: 0 auto;
}
</style>